<!-- 用户列表 -->
<template>
<div class=''>
  <!-- 面包屑导航栏 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 卡片试图区 -->
  <el-card >
    <!-- 搜索框 -->
    <el-row :gutter="20" class="user_search">
      <el-col :span="8">
        <el-input placeholder="请输入内容" v-model="searchInfo" clearable @clear="userSearch">
          <el-button slot="append" icon="el-icon-search" @click="userSearch"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="addUserDialog =true">添加用户</el-button>
      </el-col>
    </el-row>
    <!-- dialog弹窗 -->
    <el-dialog
      @closed="userFormReset"
      title="添加用户"
      :visible.sync="addUserDialog"
      width="30%">
      <!-- 内容区域 -->
      <el-form ref="form" :model="addUserForm" :rules="addUserRules"  label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" >
        <el-button @click="addUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUserList">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 表格 -->
    <el-table stripe  border  :data="userLists"
      style="width: 100%">
      <el-table-column  type="index" width="50" /> 
      <el-table-column  prop="username"  label="姓名"  width="180" />
      <el-table-column  prop="email" label="邮箱"  width="180" />
      <el-table-column  prop="mobile"  label="电话" />
      <el-table-column  prop="role_name"  label="角色" />
      <el-table-column  prop="mg_state" label="状态"  >
        <template slot-scope="scope">
          <el-switch  v-model="scope.row.mg_state" @change="userStateChange(scope.row)"/>
        </template>
      </el-table-column>
      <!-- 操作栏 -->
      <el-table-column  prop="mg_state" label="操作" width="180">
        <template slot-scope="scope" >
          <el-button type="primary" @click="getEditUser(scope.row)" icon="el-icon-edit" size="mini"></el-button>
          <el-button type="danger" @click="deleteUser(scope.row)" icon="el-icon-delete" size="mini"></el-button>
          <el-tooltip effect="dark" content="设置角色" placement="top" :enterable="false">
            <el-button type="warning" @click="setUserRole(scope.row)" icon="el-icon-setting" size="mini" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑用户dialog -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" @closed="eidtUserFormReset" >
      <el-form ref="editForm" :model="rowUserInfo" label-width="70px" :rules="addUserRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="rowUserInfo.username" disabled/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="rowUserInfo.email" />
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="rowUserInfo.mobile" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserList">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色dialog -->
    <el-dialog title="分配角色" :visible.sync="setDialogVisible" @closed="setRoleReset">
      <p class="m7">当前用户是：{{rowUserInfo.username}}</p>
      <p class="m7">当前角色是：{{rowUserInfo.role_name}}</p>
      <p class="m7">分配新角色：
        <el-select v-model="selectedRoleId" placeholder="请选择角色">
          <el-option
            v-for="item in roleLists"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUserRole(selectedRoleId)">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 删除用户提醒 -->
    <!-- 分页 -->
    <el-pagination
      class="user_page_control"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="userParams.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="userParams.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="userTotal">
    </el-pagination>
  </el-card>
</div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）

export default {
  name:'user',
 components: {},
 data() {
   var checkEmail = (rule,value,callback)=>{
     const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
     if(regEmail.test(value)){
       return callback()
    }else{
      callback(new Error('邮箱格式错误'))
    }
   }
   var checkMobile = (rule,value,callback)=>{
     const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
    if(regMobile.test(value)){
        return callback()
    }else{
      callback(new Error('请输入正确的电话号码'))
    }
   }
   return {
    addUserForm:{username:'',password:'',email:'',mobile:''},
    rowUserInfo:{},
    roleLists:{},
    selectedRoleId:'',
    addUserRules:{
      username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 2, max: 10, message: '用户名长度在 2 ~ 10 个字符之间', trigger: 'blur' }
          ],
      password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '密码长度在 6 ~ 15 个字符之间', trigger: 'blur' }
          ],
      email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator:checkEmail , trigger: 'blur' }
          ],
      mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { validator:checkMobile , trigger: 'blur' }
          ],
    },
    userTotal:0, 
    userLists:null,
    userParams:{ query:'',pagenum:1, pagesize:2 },
    searchInfo:'',
    addUserDialog:false,
    editDialogVisible:false,
    setDialogVisible:false
   };
 },
 computed: {},
 //监控data中的数据变化
 watch: {},
 //生命周期 - 创建完成（可以访问当前this实例）
 created() {
     this.getUserLists()
 },
 //生命周期 - 挂载完成（可以访问DOM元素）
 mounted() {
 
 },
 methods: {
    async getUserLists(){
      let {data:res} = await this.$http.get('users',{params:this.userParams})
      if(!res.data) return this.$message.error(res.meta.msg)
      this.userTotal = res.data.total;
      this.userLists = res.data.users;
      
    },
    handleCurrentChange(c){
      this.userParams.pagenum = c
      this.getUserLists()
    },
    handleSizeChange(c){
      this.userParams.pagesize = c
      this.getUserLists()
    },
    async userStateChange(userInfo){
      let {data:res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if(res.meta.status!==200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    userSearch(){
      this.userParams.query = this.searchInfo;
      this.getUserLists()
    },
    addUserList(){
      this.$refs.form.validate(async valid=>{
        if(!valid) return ;
        let {data:res} =  await this.$http.post('users',this.addUserForm)
        if(res.meta.status !==201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addUserDialog = false
        this.getUserLists()
      })
    },
    getEditUser(userInfo){
      this.rowUserInfo = userInfo;
      this.editDialogVisible=true
    },
    editUserList(){
      this.$refs.editForm.validate(async valid=>{
      if(!valid) return;
      let id = this.rowUserInfo.id;
      let {data:res} = await this.$http.put('users/'+id,this.rowUserInfo)
      if(res.meta.status!==200) return this.$message.error(res.meta.msg)
      this.getUserLists()
      this.editDialogVisible = false
      })
    },
    deleteUser(userInfo){
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async () => {
         let {data:res} = await this.$http.delete('users/'+userInfo.id)
         console.log(res);
         if(res.meta.status!==200) return this.$message.error(res.meta.msg)
         this.getUserLists()
         this.$message({type: 'success',message: '删除成功!'});
        })
        .catch(() => {
          this.$message({type: 'info',message: '已取消删除'});          
        });
        
    },
    userFormReset(){
      this.$refs.form.resetFields()
    },
    eidtUserFormReset(){
      this.$refs.editForm.resetFields()
    },
    setUserRole(userInfo){
      this.rowUserInfo = userInfo;
      this.setDialogVisible = true;
      this.getRoleLists()
    },
    async getRoleLists(){
      let {data:res} = await this.$http.get('roles')
      if(res.meta.status!==200) return this.$message.error(res.meta.msg)
      this.roleLists = res.data;
    },
    async saveUserRole(rid){
      if(!rid) return this.$message.error('请选择要分配的角色')
      let {data:res} = await this.$http.put(`users/${this.rowUserInfo.id}/role/`,{rid:rid})
      if(res.meta.status!==200) return this.$message.error(res.meta.msg)
      this.setDialogVisible = false;
      this.getUserLists()
      this.$message.success(res.meta.msg)
    },
    setRoleReset(){
      this.selectedRoleId = ''
    }
 },
}
</script>
<style lang="less" scoped>
.user_search{
  margin-bottom: 15px !important;
}
.user_page_control{
  margin-top: 10px;
  display: flex;
  justify-items: center;
}
</style>